package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.Func.AsyncDimFunction;
import com.atguigu.Func.AsyncDimFunction_11;
import com.atguigu.Func.MyWindowFunction;
import com.atguigu.Util.ClickHouseUtil;
import com.atguigu.Util.MyKafkaUtil;
import com.atguigu.bean.TradeTrademarkCategoryUserRefundBean;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.TimestampAssignerSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @author hjy
 * @create 2023/3/21 10:05
 */
public class Dws11_TradeTrademarkCategoryUserRefundWindow {
    public static void main(String[] args) throws Exception {
        //todo 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall-flink/check");
//        env.getCheckpointConfig().setCheckpointTimeout(60000L);
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HADOOP_USER_NAME","atguigu");
        //todo 2 从kafka(dwd_trade_order_refund)读数据
        String topic ="dwd_trade_order_refund";
        String groupID="dws_trade_trademark_category_user_refund_window";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupID));
        //todo 3 转为JSONObj对象并获取waterMark
        SingleOutputStreamOperator<JSONObject> JSONObjWithWMDS = kafkaDS.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String value) throws Exception {
                return JSONObject.parseObject(value);
            }
        })
                .assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(TimestampAssignerSupplier.of(new SerializableTimestampAssigner<JSONObject>() {
                            @Override
                            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                                return element.getLong("create_time");
                            }
                        })));
        //todo 4 转为javaBean对象 没有leftJoin就意味着不用去重
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> javaBeanDS = JSONObjWithWMDS.map(new MapFunction<JSONObject, TradeTrademarkCategoryUserRefundBean>() {
            @Override
            public TradeTrademarkCategoryUserRefundBean map(JSONObject value) throws Exception {
                HashSet<String> orderIDSet = new HashSet<>();
                orderIDSet.add(value.getString("order_id"));
                return TradeTrademarkCategoryUserRefundBean.builder()
                        .userId(value.getString("user_id"))
                        .skuId(value.getString("sku_id"))
                        .refundCount(1L)
                        .orderIdSet(orderIDSet)
                        .build();
            }
        });

        //todo 5 先关联 tm_id 和category3_id 按照 category3_id分组开窗聚合
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> javaBeanWithSKUInfoDS = AsyncDataStream.unorderedWait(javaBeanDS, new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>("DIM_SKU_INFO") {
            @Override
            public void joinDimInfo(TradeTrademarkCategoryUserRefundBean input, JSONObject dimInfo) {
                input.setCategory3Id(dimInfo.getString("CATEGORY3_ID"));
                input.setTrademarkId(dimInfo.getString("TM_ID"));
            }

            @Override
            public String getKey(TradeTrademarkCategoryUserRefundBean input) {
                return input.getSkuId();
            }
        }, 60, TimeUnit.SECONDS);

        //todo 6 分组开窗聚合
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> reduceDS = javaBeanWithSKUInfoDS.keyBy(new KeySelector<TradeTrademarkCategoryUserRefundBean, Tuple3<String,String,String>>() {
            @Override
            public Tuple3<String,String,String> getKey(TradeTrademarkCategoryUserRefundBean value) throws Exception {
                return Tuple3.of(value.getUserId(), value.getCategory3Id(), value.getTrademarkId());
            }
        })
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public TradeTrademarkCategoryUserRefundBean reduce(TradeTrademarkCategoryUserRefundBean value1, TradeTrademarkCategoryUserRefundBean value2) throws Exception {
                        value1.setRefundCount(value1.getRefundCount() + value2.getRefundCount());
                        return value1;
                    }
                }, new WindowFunction<TradeTrademarkCategoryUserRefundBean, TradeTrademarkCategoryUserRefundBean, Tuple3<String, String, String>, TimeWindow>() {
                    @Override
                    public void apply(Tuple3<String, String, String> stringStringStringTuple3, TimeWindow window, Iterable<TradeTrademarkCategoryUserRefundBean> input, Collector<TradeTrademarkCategoryUserRefundBean> out) throws Exception {
                        TradeTrademarkCategoryUserRefundBean next = input.iterator().next();
                        out.collect(MyWindowFunction.getJavabeanFields(next,window));
                    }
                });

        //todo 7 维度关联
        //从phoenix dim层查询数据 为了加快查询，使用redis做旁路缓存 完成
        //异步io减少查询等待时间 完成
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> javaBeanWithTradeMark = AsyncDataStream.unorderedWait(reduceDS, new AsyncDimFunction_11<TradeTrademarkCategoryUserRefundBean>("DIM_BASE_TRADEMARK") {
            @Override
            public void joinDimInfo(TradeTrademarkCategoryUserRefundBean input, JSONObject dimInfo) {
                input.setTrademarkName(dimInfo.getString("TM_NAME"));
            }

            @Override
            public String getId(TradeTrademarkCategoryUserRefundBean input) {
                return input.getTrademarkId();
            }
        }, 60, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> javaBeanWithCategory3 = AsyncDataStream.unorderedWait(javaBeanWithTradeMark, new AsyncDimFunction_11<TradeTrademarkCategoryUserRefundBean>("DIM_BASE_CATEGORY3") {
            @Override
            public void joinDimInfo(TradeTrademarkCategoryUserRefundBean input, JSONObject dimInfo) {
                input.setCategory3Name(dimInfo.getString("NAME"));
                input.setCategory2Id(dimInfo.getString("CATEGORY2_ID"));
            }

            @Override
            public String getId(TradeTrademarkCategoryUserRefundBean input) {
                return input.getCategory3Id();
            }
        }, 60, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> javaBeanWithCategory2 = AsyncDataStream.unorderedWait(javaBeanWithCategory3, new AsyncDimFunction_11<TradeTrademarkCategoryUserRefundBean>("DIM_BASE_CATEGORY2") {
            @Override
            public void joinDimInfo(TradeTrademarkCategoryUserRefundBean input, JSONObject dimInfo) {
                input.setCategory2Name(dimInfo.getString("NAME"));
                input.setCategory1Id(dimInfo.getString("CATEGORY1_ID"));
            }

            @Override
            public String getId(TradeTrademarkCategoryUserRefundBean input) {
                return input.getCategory2Id();
            }
        }, 60, TimeUnit.SECONDS);

        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> javaBeanWithCategory1DS = AsyncDataStream.unorderedWait(javaBeanWithCategory2, new AsyncDimFunction_11<TradeTrademarkCategoryUserRefundBean>("DIM_BASE_CATEGORY1") {
            @Override
            public void joinDimInfo(TradeTrademarkCategoryUserRefundBean input, JSONObject dimInfo) {
                input.setCategory1Name(dimInfo.getString("NAME"));
            }

            @Override
            public String getId(TradeTrademarkCategoryUserRefundBean input) {
                return input.getCategory1Id();
            }
        }, 60, TimeUnit.SECONDS);

        //todo 8 输出数据到ClickHouse
        javaBeanWithCategory1DS.print("javaBeanWithCategory1DS>>>>>>>>");
        javaBeanWithCategory1DS.addSink(ClickHouseUtil.getSinkFunction("insert into dws_trade_trademark_category_user_refund_window values(?,?,?,?,?,?,?,?,?,?,?,?,?)"));

        //todo 9 启动程序
        env.execute();
    }
}
